package com.ruoyi.web.controller.sujian;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.CxSelect;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.shiro.util.AuthorizationUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.common.exception.AirCalculateException;
import com.ruoyi.web.controller.common.exception.FuelCalculateException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 空调油费统计
 *
 * @author yangtianli
 * @date 2021-07-05
 */
@Controller
@RequestMapping("/sujian/airConditioningCostsManagement")
public class AirConditioningCostsManController extends BaseController
{
    private String prefix = "propertys/sujian/airConditioningCostsManagement";
    @Autowired
    public IFuelInfoService fuelInfoService;
    @Autowired
    public ISysParamterService sysParamterService;

    @Autowired
    public ISysFloorService sysFloorService;

    @Autowired
    public ITenantInfoService tenantInfoService;

    @Autowired
    public IAirPowerInfoService airPowerInfoService;

//    @RequiresPermissions("sujian:airConditioningCostsManagement:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FuelInfo fuelInfo){
        startPage();
        if(fuelInfo != null ){
            String etldt = fuelInfo.getEtldt();
            if(StringUtils.isNotEmpty(etldt)){
                etldt =etldt.replace("-","").substring(0,6);
                fuelInfo.setEtldt(etldt);
            }
        }
        List<FuelInfo> list = fuelInfoService.listFuelInfo(fuelInfo);
//        if (list.size()>0){
//            FuelInfo f = fuelInfoService.listAllFuelInfo(fuelInfo);
//            f.setFloorName("合计");
//            list.add(f);
//        }
        return getDataTable(list);
    }

    /**
     * 修改油费
     */
    @GetMapping("/edit/{fuelUUID}")
    public String edit(@PathVariable("fuelUUID") String fuelUUID, ModelMap mmap)
    {
        FuelInfo fuelInfo = new FuelInfo();
        fuelInfo.setFuelUUID(fuelUUID);
        mmap.put("fuel",fuelInfoService.listFuelInfo(fuelInfo).get(0));
        return prefix + "/editOil";
    }
    /**
     * 修改保存油费
     */
//    @RequiresPermissions("sujian:airConditioningCostsManagement:edit")
    @Log(title = "空调油费", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated FuelInfo fuelInfo)
    {
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(fuelInfoService.updeteFuelInfo(fuelInfo));
    }
    @GetMapping("/oilCost")
    public String oilCost(ModelMap modelMap)
    {
        //获取租户和楼层关系 取租户表即可
        //先获取楼层信息
        List<SysFloor> SysFloorList = new ArrayList<>();
        SysFloorList = sysFloorService.selectSysFloorListAll(null);
        List<CxSelect> cxList = new ArrayList<>();
        List<CxSelect>cxSelectList = new ArrayList<>();
        CxSelect cxSelect2 = new CxSelect();
        cxSelect2.setV("");
        cxSelect2.setN("所有");//楼层默认所有
        List<CxSelect> cxSelects2 = new ArrayList<>();
        CxSelect cs = new CxSelect();
        cs.setV("");
        cs.setN("所有");//租户默认所有
        cxSelects2.add(cs);
        for (SysFloor f:SysFloorList){
            CxSelect cxSelect = new CxSelect();
            TenantInfo tenantInfo = new TenantInfo();
            tenantInfo.setTenantFloor(f.getFloorName());
            List<TenantInfo> tenants = tenantInfoService.selectTenantInfoList(tenantInfo);
            List<CxSelect> cxSelects = new ArrayList<>();
            cs = new CxSelect();
            cs.setV("");
            cs.setN("所有");//每个楼层选中默认所有
            cxSelects.add(cs);
            for (TenantInfo t:tenants){
                CxSelect cxSelect1 = new CxSelect();
                cxSelect1.setN(t.getTenantName());
                cxSelect1.setV(t.getTenantId());
                cxSelects.add(cxSelect1);
                cxSelects2.add(cxSelect1);
            }
            cxSelect.setN(f.getFloorName());
            cxSelect.setV(f.getFloorId());
            cxSelect.setS(cxSelects);
            cxSelectList.add(cxSelect);
        }
        cxSelect2.setS(cxSelects2);
        cxList.add(cxSelect2);
        for (CxSelect cxSelect:cxSelectList){
            cxList.add(cxSelect);
        }//按所有在上 的顺序排序
        modelMap.put("csList", JSON.toJSON(cxList));
        return prefix + "/oilCost";
    }
//    @RequiresPermissions("sujian:airConditioningCostsManagement:calculateValue")
    @Log(title = "空调-计算油费和油费合计", businessType = BusinessType.INSERT)
    @PostMapping("/calculateValue")
    @ResponseBody
    public AjaxResult calculateValue(@Validated FuelInfo fuelInfo)
    {
        boolean falg = true;
        //获取所有楼层和租户的面积信息
        List<FuelInfo> lists  = fuelInfoService.listFuelTenantInfo();
        String ed = "";
        if (fuelInfo!=null){
            String etldt = fuelInfo.getEtldt();
            if (!"".equals(etldt) && etldt!=null) ed =etldt.replace("-","").substring(0,6);
            fuelInfo.setEtldt(ed);
            falg = fuelInfoService.deleteFuelInfo(fuelInfo)>0?true:false;
        }

//        double xs = getParamValue("kt","djz","hyfpf");
        for (FuelInfo f : lists) {
            SysFloor sysFloor = sysFloorService.selectSysFloorById(f.getFloorId());
            TenantInfo tenantInfo = tenantInfoService.selectTenantInfoById(f.getTenantId());
            FuelCalculateException calculateException = new FuelCalculateException(f,ed,fuelInfoService,sysFloor, tenantInfo);
            try{
                calculateException.start();
                falg = calculateException.getFlag();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                calculateException.interrupt();//关闭线程
            }
        }
        return toAjax(falg);
    }
    public Double getParamValue(String str1,String str2,String str3){
        double value =0.00;
        SysParamter sysParamter = new SysParamter();
        sysParamter.setParamterId(str1);
        sysParamter.setParamterLlId(str2);
        sysParamter.setParamterLl2Id(str3);
        List<SysParamter> paramterList = new ArrayList<>();
        paramterList = sysParamterService.listSysParamter(sysParamter);
        if (paramterList.size()>0)  value = Double.parseDouble(paramterList.get(0).getParamterValue());
        return value;
    }


    @Log(title = "空调油费", businessType = BusinessType.EXPORT)
//    @RequiresPermissions("sujian:airConditioningCostsManagement:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FuelInfo fuelInfo)
    {
        List<FuelInfo> list = fuelInfoService.listFuelInfo(fuelInfo);
        FuelInfo f = fuelInfoService.listAllFuelInfo(fuelInfo);
        f.setFloorName("合计");
        list.add(f);
        ExcelUtil<FuelInfo> util = new ExcelUtil<FuelInfo>(FuelInfo.class);
        return util.exportExcel(list, "空调油费");
    }

    @Log(title = "空调油费", businessType = BusinessType.IMPORT)
//    @RequiresPermissions("sujian:airConditioningCostsManagement:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<FuelInfo> util = new ExcelUtil<FuelInfo>(FuelInfo.class);
        List<FuelInfo> fuelInfoList = util.importExcel(file.getInputStream());
        List<FuelInfo> list = new ArrayList<>();
        for (FuelInfo fuelInfo:fuelInfoList){
            //查询楼层和租户的id
            String foolId = sysFloorService.selectSysFloorByName(fuelInfo.getFloorName()).getFloorId();
            TenantInfo tenantInfo = new TenantInfo();
            tenantInfo.setTenantName(fuelInfo.getTenantName());
            tenantInfo.setTenantArea(BigDecimal.valueOf(Double.parseDouble(fuelInfo.getTenantArea())));
            String tenantId = tenantInfoService.selectTenantInfoList(tenantInfo).get(0).getTenantId();
            fuelInfo.setFloorId(foolId);
            fuelInfo.setTenantId(tenantId);
            list.add(fuelInfo);
        }
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message=fuelInfoService.importFuelInfo(list,updateSupport,operName);
//        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }
//    @RequiresPermissions("sujian:airConditioningCostsManagement:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<FuelInfo> util = new ExcelUtil<FuelInfo>(FuelInfo.class);
        return util.importTemplateExcel("空调油费");
    }

    //以下为空调电费的内容

    @GetMapping("/airConditioningCost")
    public String airConditioningCost(ModelMap modelMap)
    {
        //获取租户和楼层关系 取租户表即可
        //先获取楼层信息
        List<SysFloor> SysFloorList = new ArrayList<>();
        SysFloorList = sysFloorService.selectSysFloorListAll(null);
        List<CxSelect> cxList = new ArrayList<>();
        List<CxSelect>cxSelectList = new ArrayList<>();
        CxSelect cxSelect2 = new CxSelect();
        cxSelect2.setV("");
        cxSelect2.setN("所有");//楼层默认所有
        List<CxSelect> cxSelects2 = new ArrayList<>();
        CxSelect cs = new CxSelect();
        cs.setV("");
        cs.setN("所有");//租户默认所有
        cxSelects2.add(cs);
        for (SysFloor f:SysFloorList){
            CxSelect cxSelect = new CxSelect();
            TenantInfo tenantInfo = new TenantInfo();
            tenantInfo.setTenantFloor(f.getFloorName());
            List<TenantInfo> tenants = tenantInfoService.selectTenantInfoList(tenantInfo);
            List<CxSelect> cxSelects = new ArrayList<>();
            cs = new CxSelect();
            cs.setV("");
            cs.setN("所有");//每个楼层选中默认所有
            cxSelects.add(cs);
            for (TenantInfo t:tenants){
                CxSelect cxSelect1 = new CxSelect();
                cxSelect1.setN(t.getTenantName());
                cxSelect1.setV(t.getTenantId());
                cxSelects.add(cxSelect1);
                cxSelects2.add(cxSelect1);
            }
            cxSelect.setN(f.getFloorName());
            cxSelect.setV(f.getFloorId());
            cxSelect.setS(cxSelects);
            cxSelectList.add(cxSelect);
        }
        cxSelect2.setS(cxSelects2);
        cxList.add(cxSelect2);
        for (CxSelect cxSelect:cxSelectList){
            cxList.add(cxSelect);
        }//按所有在上 的顺序排序
        modelMap.put("csList", JSON.toJSON(cxList));
        return prefix + "/airConditioningCost";
    }
//    @RequiresPermissions("sujian:airConditioningCostsManagement:airList")
    @PostMapping("/airList")
    @ResponseBody
    public TableDataInfo airList(AirPowerInfo airPowerInfo){
        startPage();
        if (airPowerInfo!=null){
            String etldt = airPowerInfo.getEtldt();
            if(StringUtils.isNotEmpty(etldt)){
                etldt = etldt.replace("-","").substring(0,6);
                airPowerInfo.setEtldt(etldt);
            }
        }
        List<AirPowerInfo> list = airPowerInfoService.listAirPowerInfo(airPowerInfo);
//        if (list.size()>0){
//            AirPowerInfo ap = airPowerInfoService.listAllPowerInfo(airPowerInfo);
//            ap.setFloorName("合计");
//            list.add(ap);
//        }
        return getDataTable(list);
    }

    /**
     * 修改油费
     */
    @GetMapping("/airEdit/{powerUUID}")
    public String airEdit(@PathVariable("powerUUID") String powerUUID, ModelMap mmap)
    {
        System.out.println(powerUUID);
        AirPowerInfo airPowerInfo = new AirPowerInfo();
        airPowerInfo.setPowerUUID(powerUUID);
        mmap.put("airPow",airPowerInfoService.listAirPowerInfo(airPowerInfo).get(0));
        return prefix + "/editAir";
    }
    /**
     * 修改保存电费
     */
//    @RequiresPermissions("sujian:airConditioningCostsManagement:airEdit")
    @Log(title = "空调电费", businessType = BusinessType.UPDATE)
    @PostMapping("/airEdit")
    @ResponseBody
    public AjaxResult airEditSave(@Validated AirPowerInfo airPowerInfo)
    {
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(airPowerInfoService.updeteAirPowerInfo(airPowerInfo));
    }

    @Log(title = "空调电费", businessType = BusinessType.EXPORT)
//    @RequiresPermissions("sujian:airConditioningCostsManagement:airExport")
    @PostMapping("/airExport")
    @ResponseBody
    public AjaxResult exportAir(AirPowerInfo airPowerInfo)
    {
        List<AirPowerInfo> list = airPowerInfoService.listAirPowerInfo(airPowerInfo);
        AirPowerInfo ap = airPowerInfoService.listAllPowerInfo(airPowerInfo);
        ap.setFloorName("合计");
        list.add(ap);
        ExcelUtil<AirPowerInfo> util = new ExcelUtil<AirPowerInfo>(AirPowerInfo.class);
        return util.exportExcel(list, "公用电空调");
    }

    @Log(title = "空调电费", businessType = BusinessType.IMPORT)
//    @RequiresPermissions("sujian:airConditioningCostsManagement:airImportData")
    @PostMapping("/airImportData")
    @ResponseBody
    public AjaxResult importDataAir(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<AirPowerInfo> util = new ExcelUtil<AirPowerInfo>(AirPowerInfo.class);
        List<AirPowerInfo> airPowerInfoList = util.importExcel(file.getInputStream());
        List<AirPowerInfo> list = new ArrayList<>();
        for (AirPowerInfo airPowerInfo:airPowerInfoList){
            //查询楼层和租户的id
            String foolId = sysFloorService.selectSysFloorByName(airPowerInfo.getFloorName()).getFloorId();
            TenantInfo tenantInfo = new TenantInfo();
            tenantInfo.setTenantName(airPowerInfo.getTenantName());
            tenantInfo.setTenantArea(BigDecimal.valueOf(Double.parseDouble(airPowerInfo.getTenantArea())));
            String tenantId = tenantInfoService.selectTenantInfoList(tenantInfo).get(0).getTenantId();
            airPowerInfo.setFloorId(foolId);
            airPowerInfo.setTenantId(tenantId);
            list.add(airPowerInfo);
        }
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message=airPowerInfoService.importAirPowerInfo(list,updateSupport,operName);
//        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }
//    @RequiresPermissions("sujian:airConditioningCostsManagement:airView")
    @GetMapping("/airImportTemplate")
    @ResponseBody
    public AjaxResult importTemplateAir()
    {
        ExcelUtil<AirPowerInfo> util = new ExcelUtil<AirPowerInfo>(AirPowerInfo.class);
        return util.importTemplateExcel("空调电费");
    }

//    @RequiresPermissions("sujian:airConditioningCostsManagement:airCalculateValue")
    @Log(title = "空调-计算电费", businessType = BusinessType.INSERT)
    @PostMapping("/airCalculateValue")
    @ResponseBody
    public AjaxResult airCalculateValue(AirPowerInfo airPowerInfo)
    {
        boolean falg = true;
        //获取所有楼层和租户的面积信息
        List<SysFloor> lists  = sysFloorService.selectSysFloorListAll(null);
        //计算公用电 及分摊金额
        String ed = "";
        if (airPowerInfo!=null){
            String etldt = airPowerInfo.getEtldt();
            if (!"".equals(etldt)) ed =etldt.replace("-","").substring(0,6);
            airPowerInfo.setEtldt(ed);
            airPowerInfoService.deleteAirPowerInfo(airPowerInfo);
        }

        for (SysFloor f : lists) {
            double gydftxs = 0.00; //公用点分摊系统
            double gydxs = 0.00;//公用电费分摊金额系数
            double ktfdxs  = 0.00;//空调电分摊参数
            double dfxs = 0.00;//空调电费分摊金额系数

            //从参数表中取  优化从楼层表中取 公共电 物业电
            gydftxs = Double.parseDouble(f.getEleSchareFeeParam());
            gydxs  = Double.parseDouble(f.getPubElecCoef());//getParamValue("xsbd","bdsx","gyd");
            ktfdxs = Double.parseDouble(f.getAirConditionShareParam());
            dfxs  = Double.parseDouble(f.getPubElecShareParam());//getParamValue("sd","pjdj","dw3");

            TenantInfo t = new TenantInfo();
            t.setTenantFloor(f.getFloorName());
            List<TenantInfo> tenantInfoList = tenantInfoService.selectTenantInfoList(t);  //获取同一楼层的所有租户
            for (TenantInfo tenant:tenantInfoList){
                AirCalculateException calculateException=null;
                try {
                    calculateException = new AirCalculateException(ed, gydftxs, dfxs, ktfdxs, gydxs, tenant, f, airPowerInfoService);
                    calculateException.start();
                    falg = calculateException.getFlag();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (calculateException != null) {
                        calculateException.interrupt();//关闭线程
                    }
                }
            }
        }
        return toAjax(falg);
    }
}
